<template>
  <div>
    <!--  -->
    <a-card :bordered="false" style="margin-top: 12px">
      <a-button @click="handleShowFilter" icon="filter"
        >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums() }}</span></a-button
      >
      <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
      <div class="right-btn"></div>
      <a-table
        row-key="id"
        :key="tableKey"
        size="middle"
        :scroll="{ x: scrollX, y: 'calc(100vh - 366px)' }"
        :hideDefaultSelections="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          columnTitle: ' ',
          onChange: onSelectChange,
          columnWidth: '60px',
        }"
        :columns="columns"
        :dataSource="modelList"
        :pagination="false"
        @change="tableChange"
        class="j-table-force-nowrap"
        :components="drag(columns, 'ACCOUNT_NOTICE')"
      >
        <div slot="topic" slot-scope="text" class="btn-text" :title="text">{{ text || '-' }}</div>
        <div slot="message" slot-scope="text" :title="text">{{ text }}</div>
        <span slot="actions" slot-scope="text, record">
          <a href="javascript:;" @click="handleDelete(record)">删除</a>
          <a href="javascript:;" @click="handleEdit(record)" v-if="record.status == '0'" style="margin-left: 20px"
            >标记已读</a
          >
        </span>
        <!-- 输入框搜索 -->
        <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
          <a-input
            placeholder="请输入"
            v-model="filterForm[column.dataIndex]"
            style="width: 188px; display: block"
            @pressEnter="handleSearch"
          />
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <a-icon
          slot="searchIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <!-- 选择搜索 -->
        <div slot="selectDropdown" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
          <a-select
            mode="multiple"
            allowClear
            placeholder="请选择"
            style="width: 200px"
            v-model="filterForm[column.dataIndex]"
          >
            <a-select-option v-for="type in selectList(column.dataIndex)" :key="type.value" :value="type.value">{{
              type.text
            }}</a-select-option>
          </a-select>
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <a-icon
          slot="selectIcon"
          slot-scope="filtered"
          type="filter"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
      </a-table>
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
    </a-card>
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums(1) }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums(1) > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="标题">
                <a-input v-model="filterForm.topic" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="消息类型">
                <a-select
                  mode="multiple"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['type']"
                >
                  <a-select-option v-for="type in noticeTypes" :key="type.value" :value="type.value">{{
                    type.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="来源模块">
                <a-select
                  mode="multiple"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['source']"
                >
                  <a-select-option v-for="type in sourceList" :key="type.value" :value="type.value">{{
                    type.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="状态">
                <a-select
                  mode="multiple"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['status']"
                >
                  <a-select-option value="0">未读</a-select-option>
                  <a-select-option value="1">已读</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="通知时间">
                <a-input v-model="filterForm.createTime" placeholder="请输入" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 全选/分页 -->
    <div
      class="uni-card resetPadding"
      :style="{
        position: 'fixed',
        bottom: 0,
        right: 0,
        zIndex: 2,
        left: collapsed ? '79px' : '208px',
        background: '#fff',
        paddingLeft: '43px',
      }"
    >
      <div style="display: inline-block">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span class="btn-text" style="margin: 0 24px" @click="batchRead">标记已读</span>
        <span class="btn-text" @click="batchAction">删除</span>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span class="btn-text" @click="clearArr" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, camelCase2UnderLine } from '@/utils/util'
import { ajaxGetDictItems, getPageList, updateStatus, mgtNoticeDelete, getDictItemsFromCache } from '@/api/api'
import { mapState } from 'vuex'
import tableDragResize from '@/mixins/tableDragResize'
// 表头
/* 打开设置列面板123 */
const columnsValue = [
  {
    title: '标题',
    width: 150,
    ellipsis: true,
    dataIndex: 'topic',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'topic',
    },
  },
  {
    title: '摘要',
    width: 240,
    ellipsis: true,
    dataIndex: 'message',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'message',
    },
  },
  {
    title: '消息类型',
    width: 100,
    ellipsis: true,
    dataIndex: 'type',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
    },
    customRender(text, record) {
      return record.typeText
    },
  },
  {
    title: '来源模块',
    width: 100,
    ellipsis: true,
    dataIndex: 'source',
    customRender(text, record) {
      return record.sourceText
    },
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
    },
  },
  {
    title: '通知时间',
    ellipsis: true,
    sorter: true,
    width: 150,
    dataIndex: 'createTime',
  },
]
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 120,
    dataIndex: 'actions',
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableDragResize],
  data() {
    return {
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      selectedRowKeys: [], // 列表已选择数据
      showSetColumn: false, // 显示
      //全选按钮
      indeterminate: false,
      checkAll: false,
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columns: [
        {
          title: '标题',
          width: 150,
          ellipsis: true,
          dataIndex: 'topic',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'topic',
          },
        },
        {
          title: '摘要',
          width: 240,
          ellipsis: true,
          dataIndex: 'message',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'message',
          },
        },
        {
          title: '消息类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'type',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
          },
          customRender(text, record) {
            return record.typeText
          },
        },
        {
          title: '来源模块',
          width: 100,
          ellipsis: true,
          dataIndex: 'source',
          customRender(text, record) {
            return record.sourceText
          },
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
          },
        },
        {
          title: '通知时间',
          ellipsis: true,
          sorter: true,
          width: 150,
          dataIndex: 'createTime',
        },
      ],
      filterForm: {},
      filteredFormLable: {
        topic: '标题',
        message: '摘要',
        type: '消息类型',
        source: '来源模块',
        createTime: '通知时间',
        status: '状态',
      },
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      tableKey: 1.9,
      noticeTypes: [],
      sourceList: [
        {text: '设备维修', value: '0'},
        {text: '设备点巡检', value: '1'},
        {text: '设备保养', value: '2'},
        {text: '零部件', value: '3'},
      ]
    }
  },
  components: {
    SetColumn,
    crumbs,
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'type' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
  },
  created() {
    this.noticeTypes = getDictItemsFromCache('notice_type')
    this.initData()
    this.requestData()
  },
  mounted() {},
  methods: {
    selectList(key) {
      if (key == 'type') {
        return this.noticeTypes
      } else {
        return this.sourceList
      }
    },
    changeStatus(v, key) {
      if (v.length == 0) {
        this.filterForm[key] = undefined
      }
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: camelCase2UnderLine(sorter.columnKey),
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    filteredNums(n) {
      let nums = 0
      if (n) {
        for (let key in this.filterForm) {
          if (this.filterForm[key]) {
            nums += 1
          }
        }
      } else {
        for (let key in this.filterForm) {
          if (this.filterForm[key]) {
            nums += 1
          }
        }
      }
      return nums
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'type') {
        this.filterForm[key] = undefined
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {}
      this.showFilter = false
      this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.ACCOUNT_NOTICE)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    },
    /* 请求列表数据 */
    requestData() {
      let obj = {...this.filterForm}
      if (obj.type) {
        obj.type = obj.type.join(',')
      }
      if (obj.source) {
        obj.source = obj.source.join(',')
      }
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.sortForm,
        ...obj,
        queryFlag: '1',
      }
      getPageList(parameter)
        .then((res) => {
          if (res.success) {
            this.total = res.result.total
            this.modelList = res.result.records
            this.checkBoxStatus()
          }
        })
        .catch((error) => {})
    },
    /* 打开设置列面板123 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(columnsValue, this.BUSI_CONST.Entity.ACCOUNT_NOTICE, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, actionArr)
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.ACCOUNT_NOTICE, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 编辑 */
    handleEdit(v) {
      updateStatus({ ids: v.id }).then((res) => {
        if (res.success) {
          this.$antdMessage.success(res.message)
          this.requestData()
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    batchRead() {
      if (this.selectedRowKeys.length > 0) {
        let ids = this.selectedRowKeys.join(',')
        updateStatus({ ids }).then((res) => {
          if (res.success) {
            this.$antdMessage.success(res.message)
            this.requestData()
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      } else {
        this.$antdMessage.info('请先选择数据')
      }
    },
    /* 详情 */
    handleDetail(v) {
      this.$router.push({
        path: '/skillManagement/BOMManagementDetail',
        query: { id: v.id },
      })
    },
    /* 删除 */
    handleDelete(v) {
      let that = this
      that.$antdConfirm({
        title: '请确定要删除此消息吗？',
        content: ``,
        onOk() {
          mgtNoticeDelete({ ids: v.id }).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('消息删除成功！')
              if (that.modelList.length === 1) {
                that.current = that.current == 1 ? 1 : that.current - 1
              }
              that.requestData()
            } else {
              that.$antdMessage.error('消息删除失败！')
            }
          })
        },
        onCancel() {},
      })
    },
    /* 列表选择 */
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量删除
    batchAction() {
      let that = this
      if (that.selectedRowKeys.length > 0) {
        let ids = that.selectedRowKeys.join(',')
        that.$antdConfirm({
          title: '请确定要删除消息吗?',
          content: `共选中${that.selectedRowKeys.length}条消息`,
          onOk() {
            that.clearArr()
            mgtNoticeDelete({ ids }).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('消息删除成功！')
                that.handleSearch()
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    /* 清除 */
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData()
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData()
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.btn-text-none {
  color: #888888;
}
a {
  margin: 0;
}
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
/deep/ .ant-card-body {
  height: calc(100vh - 214px);
  overflow: hidden;
  padding: 20px 16px;
}
</style>
